<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业实现低成本数字化转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\property\energy;

use think\App;
use app\controller\property\Base;
use app\validate\energy\EnergySharedPlanValidate;
use app\common\repositories\energy\EnergyMeterRepository;
use app\common\repositories\energy\EnergySharedPlanRepository;
use app\common\repositories\property\basic\PropertyBasicRepository;

class EnergySharedPlan extends Base
{
    protected $repository;

    public function __construct(App $app, EnergySharedPlanRepository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }


    protected function commonParams()
    {
        /** @var PropertyBasicRepository $propertyRepository */
        $propertyRepository = app()->make(PropertyBasicRepository::class);
        $propertyData = $propertyRepository->getPropertyData($this->request->propertyId, ['is_show' => 1]);

        /** * @var EnergyMeterRepository $energyMeterRepository */
        $energyMeterRepository = app()->make(EnergyMeterRepository::class);
        $energyTypeData = $energyMeterRepository::ENERGY_TYPE;
        $this->assign([
            'propertyData' => $propertyData,
            'energyTypeData' => $energyTypeData,
        ]);
    }

    /**
     * 公摊方案列表
     * @return string|\think\response\Json
     * @throws \Exception
     */
    public function list()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'property_id' => '',
                'keywords' => ''
            ]);
            [$page, $limit] = $this->getPage();
            $res = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
        $this->commonParams();
        return $this->fetch('energy/shared/plan/list', [
            'addAuth' => property_auth('propertyEnergySharedPlanAdd'),
            'editAuth' => property_auth('propertyEnergySharedPlanEdit'),
            'delAuth' => property_auth('propertyEnergySharedPlanDel'),
            'detailAuth' => property_auth('propertyEnergySharedPlanDetail'),
        ]);
    }

    /**
     * 添加公摊方案
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     */
    public function add()
    {
        if ($this->request->isAjax() && $this->request->isGet() && $this->request->param('get_type') == 'meterData') {
            $energyType = $this->request->param('energy_type');
            /** * @var EnergyMeterRepository $energyMeterRepository */
            $energyMeterRepository = app()->make(EnergyMeterRepository::class);
            $meterData = $energyMeterRepository->getSearch([])
                ->where('is_bind', 2)
                ->where('is_public', 1)
                ->where('plan_type', 1)
                ->where('energy_type', $energyType)
                ->where('plan_id', '>', 0)
                ->field('id,energy_no,energy_name')
                ->select()->toArray();
            return json()->data(['code' => 0, 'data' => $meterData]);
        } else if ($this->request->isPost()) {
            $param = $this->request->param([
                'plan_name' => '',
                'property_id' => '',
                'plan_type' => '',
                'is_type' => '',
                'energy_id' => '',
                'energy_type' => '',
                'remark' => '',
            ]);
            validate(EnergySharedPlanValidate::class)->scene('add')->check($param);
            /** * @var EnergyMeterRepository $energyMeterRepository */
            $energyMeterRepository = app()->make(EnergyMeterRepository::class);
            $meterInfo = $energyMeterRepository->get($param['energy_id']);
            if (!$meterInfo) {
                return $this->error('设备不存在');
            }
            if ($meterInfo['is_bind'] == 1) {
                return $this->error('此设备已绑定');
            }
            if ($meterInfo['plan_id'] <= 0) {
                return $this->error('此设备未绑定计费方案');
            }
            try {
                $res = $this->repository->addInfo($param, $this->request->propertyId, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('录入公摊方案失败', $e);
                return $this->error('网络错误');
            }
        } else {
            $this->commonParams();
            $propertyId = (int)$this->request->param('property_id');
            return $this->fetch('energy/shared/plan/add', [
                'propertyId' => $propertyId,
            ]);
        }
    }

    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($id);

        if ($this->request->isPost()) {
            $param = $this->request->param([
                'plan_name' => '',
                'plan_type' => '',
                'is_type' => '',
                'remark' => '',
            ]);
            validate(EnergySharedPlanValidate::class)->scene('edit')->check($param);
            try {
                $res = $this->repository->editInfo($info, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                exception_log('公摊方案修改失败', $e);
                return $this->error('网络错误');
            }
        } else {
            $this->commonParams();
            return $this->fetch('energy/shared/plan/edit', [
                'info' => $info,
            ]);
        }
    }

    public function detail()
    {
        $planId = (int)$this->request->param('plan_id');
        if ($planId <= 0) {
            return $this->error('参数错误');
        }
        $planInfo = $this->repository->getDetail($planId);
        if ($planInfo['id'] <= 0) {
            return $this->error('方案信息不存在');
        }
        return $this->fetch('energy/shared/plan/detail', [
            'planInfo' => $planInfo,
            'addRoomAuth' => property_auth('propertyEnergySharedRoomAdd'),
            'editRoomAuth' => property_auth('propertyEnergySharedRoomEdit'),
            'detailRoomAuth' => property_auth('propertyEnergySharedRoomDetail'),
            'delRoomAuth' => property_auth('propertyEnergySharedRoomDel'),
        ]);
    }


    public function del()
    {
        $ids = (array)$this->request->param('ids');
        try {
            $data = $this->repository->batchDelete($ids, $this->request->userId);
            if ($data) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            exception_log('公摊方案删除失败', $e);
            return $this->error('网络失败');
        }
    }

}